package mi.payment.controller;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import mi.payment.BuildConfig;
import mi.payment.R;
import mi.payment.constants.BaseErrorCode;
import mi.payment.constants.Params;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.settings.TerminalKeyManagementBean;
import mi.payment.ui.admin.TerminalKeyManagementActivity;
import mi.payment.ui.base.OneButtonDialog;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.MustParameterCalibration;
import mi.payment.utils.iso8583.Utils;
import mi.payment.utils.secure.TerminalSecure;
import mi.payment.utils.transaction.TMKDownloadTask;
import sunmi.sunmiui.dialog.DialogCreater;
import sunmi.sunmiui.dialog.EditTextDialog;
import sunmi.sunmiui.dialog.HintDialog;
import sunmi.sunmiui.dialog.ListDialog;

/**
 * 终端密钥管理设置的默认Controller
 *
 * @author Created by Lee64 on 2017/7/19.
 */

public abstract class BaseTerminalKeyManagementController extends BaseController {

    private HintDialog hintDialog;
    private ListDialog listDialog;
    private EditTextDialog editTextDialog;
    public OneButtonDialog oneButtonDialog;
    private TerminalKeyDataOperations terminalKeyDataOperations;

    public BaseTerminalKeyManagementController(ParentActivity activity) {
        super(activity);
    }

    public void setTerminalKeyDataOperations(TerminalKeyDataOperations operations) {
        terminalKeyDataOperations = operations;
    }

    /**
     * 某些通道会定制化UI，子类可复写此方法
     */
    public int getContentLayout() {
        return R.layout.activity_terminal_key_management;
    }

    /**
     * 某些通道会定制化初始化，子类可复写此方法
     */
    public void init() {

    }

    public void onDestroy() {
        if (hintDialog != null) {
            hintDialog.dismiss();
            hintDialog = null;
        }
        if (listDialog != null) {
            listDialog.dismiss();
            listDialog = null;
        }
        if (editTextDialog != null) {
            editTextDialog.dismiss();
            editTextDialog = null;
        }
        if (oneButtonDialog != null) {
            oneButtonDialog.dismiss();
            oneButtonDialog = null;
        }
    }

    /**
     * 是否隐藏设置主密钥索引,默认为false
     */
    public boolean isHideTerminalMasterKeyIndex() {
        return false;
    }

    /**
     * 是否隐藏终端主密钥下载,默认为false
     */
    public boolean isHideTerminalMasterKeyDownload() {
        return false;
    }

    /**
     * 是否隐藏手输终端主密钥,true
     */
    public boolean isShowTerminalMasterKeyInput() {
        return true;
    }

    /**
     * 是否隐藏设置KEK,默认为false
     */
    public boolean isHideSetKEK() {
        return false;
    }

    /**
     * 是否隐藏设置DES算法,默认为false
     */
    public boolean isHideDesAlgorithms() {
        return false;
    }

    /**
     * 是否隐藏设置母POS导入密钥,默认为false
     */
    public boolean isHideParentPosImportKey() {
        return false;
    }

    /**
     * 是否隐藏设置IC卡导入,默认为false
     */
    public boolean isHideICParameterImport() {
        return false;
    }

    /**
     * 下载主密钥时是否要校验商户号和终端号,默认为true
     */
    public boolean isCheckMerchantParams() {
        return true;
    }

    /**
     * 是否弹出输入初始密钥的对话框,默认为false
     */
    public boolean isInputInitSecretKey() {
        return false;
    }

    protected void showInputErrorToast() {
        showToast(R.string.error_input);
    }

    protected void showSoftKeyboard() {
        if (editTextDialog != null) {
            editTextDialog.showSoftInput();
        }
    }

    private void updateUI() {
        if (activity instanceof TerminalKeyManagementActivity) {
            TerminalKeyManagementActivity terminalKeyManagementActivity = (TerminalKeyManagementActivity) activity;
            terminalKeyManagementActivity.updateUI();
        }
    }

    /**
     * 设置终端密钥索引
     */
    public void setTerminalMasterKeyIndex() {
        editTextDialog = DialogCreater.createEditTextDialog(activity, getString(R.string.cancel),
                getString(R.string.ok), getString(R.string.terminal_master_key_index),
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        editTextDialog.dismiss();
                    }

                },
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String text = editTextDialog.getText();
                        if (text != null && text.length() > 0) {
                            terminalKeyDataOperations.saveTerminalKeyIndex(text);
                            editTextDialog.dismiss();
                            TerminalSecure.initKeyIndex();
                            updateUI();
                        } else {
                            showInputErrorToast();
                        }
                    }

                },
                new DialogInterface.OnShowListener() {

                    @Override
                    public void onShow(DialogInterface dialog) {
                        editTextDialog.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                        showSoftKeyboard();
                    }

                }
        );
        String index = terminalKeyDataOperations.getTerminalKeyIndex();
        if (index != null && index.length() > 0) {
            editTextDialog.setText(index);
        } else {
            String str = getString(R.string.return_unknow);
            editTextDialog.setHintText(str);
        }
        editTextDialog.setMaxLength(2);
        editTextDialog.show();
    }

    /**
     * 手输终端密钥
     */
    public void setTerminalMasterKey() {
        editTextDialog = DialogCreater.createEditTextDialog(activity, getString(R.string.cancel),
                getString(R.string.save), getString(R.string.terminal_master_key),
                new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        editTextDialog.dismiss();
                    }

                }, new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        String text = editTextDialog.getText();
                        if (text != null && text.length() > 0) {
                            if (text.length() == 32) {
                                int result = -1;
                                try {
                                    byte[] tmkBytes = Utils.hexStr2Bytes(text);
                                    result = TerminalSecure.SaveTMK(tmkBytes);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (result == 0) {
                                    editTextDialog.dismiss();
                                    showToast(R.string.terminal_master_key_download_success);
                                } else {
                                    showToast(R.string.terminal_master_key_download_retry);
                                }
                            } else {
                                showInputErrorToast();
                            }
                        } else {
                            showInputErrorToast();
                        }
                    }

                }, new DialogInterface.OnShowListener() {

                    @Override
                    public void onShow(DialogInterface dialog) {
                        showSoftKeyboard();
                    }

                });
        editTextDialog.setHintText("请输入终端主密钥");
        editTextDialog.setMaxLength(32);
        editTextDialog.show();
    }

    /**
     * 下载TMK
     */
    public void downloadTMK() {
        boolean isCheckMerchantParams = isCheckMerchantParams();
        boolean isInputInitSecretKey = isInputInitSecretKey();
        if (isCheckMerchantParams) {
            boolean isNull = MustParameterCalibration.isNullMerchantAndTerminal();
            if (isNull) {
                showToast(R.string.system_errorcode);
            } else {
                if (isInputInitSecretKey) {
                    showDownloadTMKDialog();
                } else {
                    requestDownloadTMK();
                }
            }
        } else {
            if (isInputInitSecretKey) {
                showDownloadTMKDialog();
            } else {
                requestDownloadTMK();
            }
        }
    }

    public void showDownloadTMKDialog() {
        String title;
        switch (BuildConfig.FLAVOR) {
            case "lePos": // 乐刷
                title = "请输入授权码";
                break;
            default:
                title = getString(R.string.please_input_start_key);
                break;
        }
        editTextDialog = DialogCreater.createEditTextDialog(activity, getString(R.string.cancel), getString(R.string.ok), title,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        editTextDialog.dismiss();
                    }

                }, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String key = editTextDialog.getText();
                        if (key != null && key.length() > 0) {
                            if (key.length() % 8 != 0) {
                                showToast(R.string.lenght_8);
                            } else {
                                Params.CONFIG_PARAMS.put(Params.START_KEY, key);
                                editTextDialog.dismiss();
                                requestDownloadTMK();
                            }
                        } else {
                            showToast(R.string.start_key_not_null);
                        }
                    }

                }, new DialogInterface.OnShowListener() {

                    @Override
                    public void onShow(DialogInterface dialog) {
                        editTextDialog.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                        showSoftKeyboard();
                    }

                });
        editTextDialog.show();
    }

    /**
     * 终端主密钥下载
     */
    public void requestDownloadTMK() {
        @SuppressLint("StaticFieldLeak")
        TMKDownloadTask task = new TMKDownloadTask(activity) {

            @Override
            protected void onPreExecuteImpl() {
                oneButtonDialog = OneButtonDialog.createOneButtonDialog(activity);
                oneButtonDialog.setClickAble(false);
                switch (BuildConfig.FLAVOR) {
                    case "lePos": // 乐刷
                        oneButtonDialog.setTitle("请输入授权码");
                        oneButtonDialog.setMsg("正在连网激活，请稍后");
                        break;
                }
                oneButtonDialog.show();
            }

            @Override
            protected void onPostExecuteImpl(String ret) {
                oneButtonDialog.setClickAble(true);
                if ( TextUtils.equals("00", ret) ) {
                    switch (BuildConfig.FLAVOR) {
                        case "lePos": // 乐刷
                            oneButtonDialog.setMsg("参数已更新，您的POS终端激活成功");
                            break;
                        default:
                            oneButtonDialog.setMsg(R.string.terminal_master_key_download_success);
                            break;
                    }
                } else {
                    String code = BaseErrorCode.getCode(ret);
                    oneButtonDialog.setMsg(code);
                }
            }

            @Override
            protected void onTaskTimeoutImpl() {
                oneButtonDialog.setClickAble(true);
                String str = getString(R.string.download_failed) + ": " + BaseErrorCode.getCode("68");
                oneButtonDialog.setMsg(str);
            }

        };
        task.execute();
    }

    /**
     * 手输KEK
     */
    public void downloadKEK() {
        editTextDialog = DialogCreater.createEditTextDialog(activity, getString(R.string.cancel),
                getString(R.string.ok), getString(R.string.terminal_key_set_kek),
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        editTextDialog.dismiss();
                    }

                },
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String text = editTextDialog.getText();
                        if (text != null && text.length() > 0) {
                            if (text.length() == 32) {
                                int ret = TerminalSecure.saveKEK(text);
                                if (ret == 0) {
                                    terminalKeyDataOperations.saveKEK(text);
                                    editTextDialog.dismiss();
                                    updateUI();
                                    showToast(R.string.save_kek_success);
                                } else {
                                    showToast(R.string.save_kek_error);
                                }
                            } else {
                                showInputErrorToast();
                            }
                        } else {
                            showInputErrorToast();
                        }
                    }

                },
                new DialogInterface.OnShowListener() {

                    @Override
                    public void onShow(DialogInterface dialog) {
                        showSoftKeyboard();
                    }

                }
        );
        String str = getString(R.string.return_unknow);
        editTextDialog.setHintText(str);
        editTextDialog.setMaxLength(32);
        editTextDialog.show();
    }

    public void showDesAlgorithmsDialog() {
        String[] data = {getString(R.string.single_des), getString(R.string.three_des)};
        listDialog = DialogCreater.createListDialog(activity, getString(R.string.set_to), getString(R.string.cancel), data);
        listDialog.setItemClickListener(new ListDialog.ItemClickListener() {

            @Override
            public void OnItemClick(int position) {
                if (position == 0) {
                    terminalKeyDataOperations.saveDes(TerminalKeyManagementBean.SINGLE_DES);
                    listDialog.dismiss();
                    updateUI();
                } else if (position == 1) {
                    terminalKeyDataOperations.saveDes(TerminalKeyManagementBean.THREE_DES);
                    listDialog.dismiss();
                    updateUI();
                }
            }

        });
        listDialog.show();
    }

    public void ICParameterImport() {
        String[] data = {getString(R.string.tongyong), getString(R.string.shenyinlian)};
        listDialog = DialogCreater.createListDialog(activity, getString(R.string.set_to), getString(R.string.cancel), data);
        listDialog.setItemClickListener(new ListDialog.ItemClickListener() {

            @Override
            public void OnItemClick(int position) {
                switch (position) {
                    case 0:
                        terminalKeyDataOperations.saveIcImportKey(TerminalKeyManagementBean.IC_IMPORT_KEY1);
                        listDialog.dismiss();
                        updateUI();
                        break;
                    case 1:
                        terminalKeyDataOperations.saveIcImportKey(TerminalKeyManagementBean.IC_IMPORT_KEY2);
                        listDialog.dismiss();
                        updateUI();
                        break;
                }
            }

        });
        listDialog.show();
    }


}
